//
//  WFComposeTV+Extension.swift
//  WangFangWeiBo
//
//  Created by 王方 on 16/7/21.
//  Copyright © 2016年 wf. All rights reserved.
//

import UIKit

extension WFComposeTV {
    // MARK:  - 根据textview里面富文本获取对应的字符串
    var emoticonStr:String {
        
        var result = ""
        self.attributedText.enumerateAttributesInRange(NSMakeRange(0, self.attributedText.length), options: []) { (infoDic, range, _) -> Void in
            if let attachment = infoDic["NSAttachment"] as? WFTextAttachment {
                
                let chs = attachment.emoticon!.chs!
                //拼接表情描述
                result += chs
                
            } else {
                //文字
                //获取指定范围内的文字
              let text = self.attributedText.attributedSubstringFromRange(range).string
                result += text
            
            }
        }
        return result
    }
    
    // MARK:  - 根据表情模型添加富文本
    func insertEmoticon(emotion:WFEmoticon){
        if emotion.type == "0" {
        
            //取出上一次的富文本
            let originalAttributedAtr = NSMutableAttributedString(attributedString: self.attributedText)
            
            let attributedStr = NSAttributedString.attributedStringWithEmoticon(emotion, font: UIFont.systemFontOfSize(HomeFontSize))
            
            var range = self.selectedRange
            
            originalAttributedAtr.replaceCharactersInRange(range, withAttributedString: attributedStr)
            
            //5.指定富文本字体大小
            originalAttributedAtr.addAttribute(NSFontAttributeName, value: self.font!, range: NSMakeRange(0, originalAttributedAtr.length))
            
            self.attributedText = originalAttributedAtr
            
            range.location += 1; range.length = 0
            self.selectedRange = range
            
            //自己发送文字改变的通知
            NSNotificationCenter.defaultCenter().postNotificationName(UITextViewTextDidChangeNotification, object: nil)
            self.delegate?.textViewDidChange?(self)
            
        }else{
             let emoji =  (emotion.code! as NSString).emoji()
            self.insertText(emoji)
        }
        
        
    }

}
